package com.zdsx.config;

import lombok.Getter;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

@Getter
public final class LogResponse extends JsonPayload {
    private final int status;

    public LogResponse(ContentCachingResponseWrapper response) {
        super(getPayload(response, response.getCharacterEncoding(), response.getContentType()), getHeaders(response));
        this.status = response.getStatus();
    }

    public static Map<String, String> getHeaders(ContentCachingResponseWrapper response) {
        LinkedHashMap<String, String> singleValueMap = new LinkedHashMap<>();
        Collection<String> names = response.getHeaderNames();
        for (String headerName : names) {
            singleValueMap.put(headerName, response.getHeader(headerName));
        }
        return singleValueMap;
    }

    private static String getPayload(ContentCachingResponseWrapper response, String characterEncoding, String contentType) {
        if (!isJson(contentType)) {
            if (isText(contentType)) {
                StringBuffer sb = new StringBuffer();
                sb.append(JsonStringBuilder.WRAP);
                JsonStringBuilder.escape(toString(response.getContentAsByteArray(), characterEncoding), sb);
                sb.append(JsonStringBuilder.WRAP);
                return sb.toString();
            } else {
                return null;
            }
        }
        return toString(response.getContentAsByteArray(), characterEncoding);
    }
}
